<template>
  <div >
    <x-card v-if="hasPerm('sysUser:page')">
      <div slot="content" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="关键词" >
                <a-input v-model="queryParam.searchValue" allow-clear placeholder="请输入姓名、账号、手机号"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam.searchStatus" allow-clear placeholder="请选择状态" default-value="0">
                  <a-select-option v-for="(item,index) in statusDictTypeDropDown" :key="index" :value="item.code" >{{ item.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </x-card>
    <a-card :bordered="false">
      <super-table
        :pageSize="10"
        size="small"
        ref="table"
        :columns="columns"
        :data="loadData"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,columnWidth:40 }"
        :rowKey="(record) => record.id"
      >
        <template slot="operator">
          <a-button type="primary" v-if="hasPerm('sysUser:add')" icon="plus" @click="$refs.addForm.add()">新增用户</a-button>
<!--          <a-button type="primary" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('sysUser:delete')" @click="batchOpen">批量启用</a-button>-->
          <a-button type="danger" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('sysUser:delete')" @click="batchDelete">批量禁用</a-button>

          <x-down
            v-if="hasPerm('sysUser:export')"
            ref="batchExport"
            @batchExport="batchExport"
          />
        </template>
        <!--        <span slot="sex" slot-scope="text">-->
        <!--            {{ sexFilter(text) }}-->
        <!--          </span>-->
        <span slot="status" slot-scope="text,record,index" v-if="hasPerm('sysUser:changeStatus')">
            <a-switch checked-children="开" un-checked-children="关" @change="e =>changeSwitch(e,record,index)" :checked="numberToBoolean(text)"  />
        </span>
        <span slot="action" slot-scope="text, record">
          <a v-if="hasPerm('sysUser:edit')" @click="$refs.editForm.edit(record)">编辑</a>
          <a-divider type="vertical" v-if="hasPerm('sysUser:edit')" />
          <a-dropdown v-if="hasPerm('sysUser:resetPwd') || hasPerm('sysUser:grantRole') || hasPerm('sysUser:grantData') || hasPerm('sysUser:delete')">
            <a class="ant-dropdown-link">
              更多 <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-if="hasPerm('sysUser:resetPwd')">
                <a-popconfirm placement="topRight" title="确认重置密码？" @confirm="() => resetPwd(record)">
                  <a>重置密码</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-if="hasPerm('sysUser:grantRole')">
                <a @click="$refs.userRoleForm.userRole(record)">授权角色</a>
              </a-menu-item>
              <a-menu-item v-if="hasPerm('sysUser:grantData')">
                <a @click="$refs.userOrgForm.userOrg(record)">授权数据</a>
              </a-menu-item>
              <a-menu-item v-if="hasPerm('sysUser:delete')">
                <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => singleDelete(record)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </super-table>
      <add-form ref="addForm" @ok="handleOk" />
      <edit-form ref="editForm" @ok="handleOk" />
      <user-role-form ref="userRoleForm" @ok="handleOk"/>
      <user-org-form ref="userOrgForm" @ok="handleOk"/>
    </a-card>
  </div>

</template>

<script>

import { STable, SuperTable, XCard, XDown } from '@/components'
import moment from 'moment'
import addForm from '@/views/baseData/organizationFramework/user/addForm'
import editForm from '@/views/baseData/organizationFramework/user/editForm'
import userRoleForm from '@/views/baseData/organizationFramework/user/userRoleForm'
import userOrgForm from '@/views/baseData/organizationFramework/user/userOrgForm'
import { sysDictTypeDropDown } from '@/api/modular/system/dictManage'
import { sysUserExport, getUserPageNew, sysUserChangeStatus } from '@/api/modular/system/userManage'
export default {
  components: {
    SuperTable,
    XDown,
    XCard,
    STable,
    addForm,
    editForm,
    userRoleForm,
    userOrgForm
  },
  data() {
    return {
      // 加载数据方法 必须为 Promise 对象，由于parameter自带pageNum和pageSize参数，
      // 因此queryParam不能携带pageNum和pageSize参数，否则会替换掉，可携带其他参数
      loadData: parameter => {
        return getUserPageNew(Object.assign(parameter, this.queryParam)).then((res) => {
          // console.log('新组织架构，用户列表',res)
          this.tableData =res.rows
          return res
        })
      },
      tableData:[],
      columns: [
        // { title: '序号', customRender: (text,record,index) => index+1 },
        { title: '账号', dataIndex: 'account' },
        { title: '姓名', dataIndex: 'name',width:100 },
        { title: '部门职务', dataIndex: 'pos' ,width:150,ellipsis:true},
        { title: '角色', dataIndex: 'role' },
        { title: '性别', dataIndex: 'sex', scopedSlots: { customRender: 'sex' } ,width:80},
        { title: '手机', dataIndex: 'phone' },
        { title: '状态', dataIndex: 'status', scopedSlots: { customRender: 'status' } }
      ],
      rowSelection: {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      },
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      selectedRowKeys: [],
      statusDictTypeDropDown: [],
      form: this.$form.createForm(this),
      // 查询参数
      queryParam: {},
      loading: true, //加载状态,
      currentActiveKey: 1,
    }
  },
  created() {
    this.sysDictTypeDropDown()
    if (this.hasPerm('sysUser:edit') || this.hasPerm('sysUser:resetPwd') || this.hasPerm('sysUser:grantRole') || this.hasPerm('sysUser:grantData') || this.hasPerm('sysUser:delete')) {
      this.columns.push({
        title: '操作',
        width: '150px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
  },
  methods: {
    moment,
    /**
     * 获取字典数据
     */
    sysDictTypeDropDown (text) {
      sysDictTypeDropDown({ code: 'sex' }).then((res) => {
        this.sexDictTypeDropDown = res.data
      })
      sysDictTypeDropDown({ code: 'common_status' }).then((res) => {
        this.statusDictTypeDropDown = res.data
      })
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    sexFilter (sex) {
      // eslint-disable-next-line eqeqeq
      const values = this.sexDictTypeDropDown.filter(item => item.code == sex)
      if (values.length > 0) {
        return values[0].value
      }
    },
    numberToBoolean(text){
      return typeof (text) =='boolean' ? text :(text == 0 ? false : true)
    },
    /**
     * 修改用户状态
     */
    changeSwitch(value,record,index){
      console.log('record',record)
      console.log('status',value)
      this.tableData[index].status = value
      sysUserChangeStatus({ id: record.id, status: value?1:0 }).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          // this.$refs.table.refresh()
        } else {
          this.$message.error('操作失败：' + res.message)
        }
      })
    },
    statusFilter (status) {
      // eslint-disable-next-line eqeqeq
      const values = this.statusDictTypeDropDown.filter(item => item.code == status)
      if (values.length > 0) {
        return values[0].value
      }
    },
    /**
     * 单个删除
     */
    singleDelete (record) {
      const param = [{ 'id': record.id }]
      this.sysUserDelete(param)
    },
    /**
     * 批量启用
     */
    batchOpen () {
      const paramIds = this.selectedRowKeys.map((id) => {
        return { 'id': id }
      })
      console.log('批量启用数组',paramIds)
    },
    /**
     * 批量删除
     */
    batchDelete () {
      const paramIds = this.selectedRowKeys.map((d) => {
        return { 'id': d }
      })
      this.sysUserDelete(paramIds)
    },
    changeTabs(key) {
      this.currentActiveKey = key
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },

    /**
     * 批量导出
     */
    batchExport () {
      sysUserExport().then((res) => {
        this.$refs.batchExport.downloadfile(res)
      })
    },
  }

}
</script>

<style lang="less" scoped>

.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
  margin-bottom: 2px;
}

.currentRowClass {
  background: #e6f7ff;
}

/deep/ .ant-tabs-bar {
  border-bottom: none;
  margin: -24px;
}

/deep/ .table-search-page .ant-tabs-nav-wrap{
  background: #ffffff;
}

</style>